package com.ficus.road.maintain.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.ficus.road.maintain.core.model.taskInfo.CDResponse;
import com.ficus.road.maintain.core.model.taskInfo.CDTaskInfoDetail;
import com.ficus.road.maintain.core.model.taskInfo.TaskInfoDetail;
import com.ficus.road.maintain.core.model.taskInfo.TaskInfoResponse;
import com.ficus.road.maintain.core.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lijiawei
 * @date 2023/10/10 上午10:45
 */

@Component
@Slf4j
public class ZHCDClient {

    public static final String SUCCESS_CODE = "200";

    public static final String UNAUTHORIZED = "401";

    @Autowired
    private RestTemplate restTemplate;

    @Value("${xlj.user-name}")
    private String userName;
    @Value("${xlj.pass-word}")
    private String passWord;
    @Value("${xlj.server}")
    private String server;

    private String cookie = "";

    // 获取城道接口Cookie
    public String logInAndRequestCookie() {
        String url = server + "/user/login";
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("userName", userName);
        params.add("password", passWord);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建一个表单请求对象
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

        // 发送 POST 请求并获取响应
        ResponseEntity<JsonNode> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JsonNode.class);
        return responseEntity.getHeaders().get("Set-Cookie").get(0);
    }

    public String getWebServiceResponse(String url, HttpMethod method) {
        return getWebServiceResponse(url, method, false);
    }
    public String getWebServiceResponse(String url, HttpMethod method, boolean retry) {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (retry) {
            cookie = logInAndRequestCookie();
        }
        httpHeaders.set("Cookie", cookie);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(httpHeaders);
        try {
            ResponseEntity<JsonNode> exchange = restTemplate.exchange(url, method, requestEntity, JsonNode.class);
            if (exchange != null && exchange.hasBody() && exchange.getBody().get("code")!= null) {
                JsonNode body = exchange.getBody();
                String code = body.get("code").asText();
                if (SUCCESS_CODE.equals(code))
                    return body.get("data").toString();
                else if (UNAUTHORIZED.equals(code) && !retry) {
                    return getWebServiceResponse(url, method, true);
                }
            }
            return null;
        } catch (Exception e) {
            log.error("中海城道接口请求异常",e.getMessage());
            return null;
        }

    }
    public String getReasonFromZhongHaiCDTaskInfo(String taskNum) {
        String response = getZhongHaiCDTaskInfo(taskNum);
        if (response != null) {
            return retrieveReasonFromCDTaskInfoResponse(response);
        }
        return null;
    }

    // 获取城道接口案卷流程信息
    public String getZhongHaiCDTaskInfo(String taskNum) {
        String url = server + "/flowInfo/" + taskNum;
        String webServiceResponse = getWebServiceResponse(url, HttpMethod.GET);
        if (webServiceResponse == null) {
            log.error("中海城道接口获取流程异常,流程id = {}", taskNum);
        }
        return webServiceResponse;
    }

    public String retrieveReasonFromCDTaskInfoResponse(String response) {
        try {
            TypeReference<List<CDTaskInfoDetail>> ref = new TypeReference<List<CDTaskInfoDetail>>() {};
            List<CDTaskInfoDetail> taskInfoResponseList = JsonUtils.StringConvertToList(response, ref);
            List<CDTaskInfoDetail> collect = taskInfoResponseList.stream().sorted(Comparator.comparing(CDTaskInfoDetail::getCreateTime).reversed()).collect(Collectors.toList());
            for (CDTaskInfoDetail taskInfoDetail : collect) {
                if (taskInfoDetail.isRejectInfo()) {
                    return taskInfoDetail.getAdvice();
                }
            }
            // 无退单数据
            return null;
        } catch (Exception e) {
            log.error("退单结果解析失败, response = {}",response);
            return null;
        }
    }

}
